package com.example.administrator.text;

import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import data.SharedPreferencesUtils;
import util.AgentIp;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.getInformation;
import view.diaLogView.UploadDialog;

public class PingActivity extends BaseActivity {
    private String mIP,mNetwork,mNetFwq,mFwq,mCurrentFWQ;
    private Logger mLogger = Logger.getLogger(AgentIp.class);
    private WebView mWebView;
    final String[] usermac = {""};
    final String[] nasid = {""};
    private UploadDialog mUploadDialog;
    private boolean mJumd = true;          //判断第几次加载网页
    private TextView mTViewNasid;
    private ImageView mImageViewIP,mImageViewWay,mImageViewAgentFwq,mImageViewFwq,mImageViewNiuLang,mImageViewAiLi;// ip  网关 代理服务器 服务器 牛郎官网 阿里
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            String type = (String) bundle.get("type");
            int state = bundle.getInt("state");
            LogUtil.eE("","handleMessage------------type"+type+" state    "+state);
            if(type.equals("ip")){
                if(state == 0){
                    mImageViewIP.setImageResource(R.mipmap.wifl_network);
                }else {
                    mImageViewIP.setImageResource(R.mipmap.fork);
                }
            }else if(type.equals("work")){
                if(state == 0){
                    mImageViewWay.setImageResource(R.mipmap.wifl_network);
                }else {
                    mImageViewWay.setImageResource(R.mipmap.fork);
                }
            }else if(type.equals("netFwq")){
                if(state == 0){
                    mImageViewAgentFwq.setImageResource(R.mipmap.wifl_network);
                }else {
                    mImageViewAgentFwq.setImageResource(R.mipmap.fork);
                }
            }else if(type.equals("fwq")){
                if(state == 0){
                    mImageViewFwq.setImageResource(R.mipmap.wifl_network);
                }else {
                    mImageViewFwq.setImageResource(R.mipmap.fork);
                }
            }else if(type.equals("taobao")){
                if(state == 0){
                    mImageViewAiLi.setImageResource(R.mipmap.wifl_network);
                }else {
                    mImageViewAiLi.setImageResource(R.mipmap.fork);
                }
            }else if(type.equals("altair")){
                if(state == 0){
                    mImageViewNiuLang.setImageResource(R.mipmap.wifl_network);
                }else {
                    mImageViewNiuLang.setImageResource(R.mipmap.fork);
                }
            }
        }
    };

    @Bind(R.id.ping_frame)                FrameLayout mFrameLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ping);

        ButterKnife.bind(this);
        HomeUtil.getHemeUtilNew().getStatusBar(this,mFrameLayout);
        init();
    }

    /**
     * 返回
     */
    @OnClick(R.id.image_ping) void aboutReturn(){
        finish();
    }

    /**
     * 提交Nasid
     */
    @OnClick(R.id.text_wifimac_nasid)
    void onNasid(){
        pustApMacNasid(nasid[0],usermac[0]);
    }

    private void init(){
        TextView textViewName = (TextView) findViewById(R.id.text_wifinaem_ping);
        TextView textViewMac = (TextView) findViewById(R.id.text_wifimac_ping);
        final TextView textViewIp = (TextView) findViewById(R.id.text_wifiip_ping);
        TextView tVsiteareaid = (TextView) findViewById(R.id.text_siteareaid_ping);
        TextView tVid = (TextView) findViewById(R.id.text_userid_ping);
        final TextView textViewNetwork = (TextView) findViewById(R.id.text_wifinetwork_ping);
        final TextView textViewAgentFwq = (TextView) findViewById(R.id.text_wifi_agentfwq_ping);
        final TextView textViewFWQ = (TextView) findViewById(R.id.text_wififwq_ping);
        final TextView TViewCurrentFWQ = (TextView) findViewById(R.id.text_niulang_ping);  //当前服务器
        mTViewNasid= (TextView) findViewById(R.id.text_wifimac_nasid);  //Nadis
        TextView apMac = (TextView) findViewById(R.id.text_wifimac_apMac);
        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linea_agentfwq_ping);
        mImageViewIP = (ImageView)findViewById(R.id.image_wifiip_ping);
        mImageViewWay = (ImageView)findViewById(R.id.image_wifinetwork_ping);
        mImageViewAgentFwq = (ImageView)findViewById(R.id.image_wifi_agentfwq_ping);
        mImageViewFwq = (ImageView)findViewById(R.id.image_wifi_networkping);
        mImageViewNiuLang = (ImageView)findViewById(R.id.image_niulang_ping);
        mImageViewAiLi = (ImageView)findViewById(R.id.image_taobao_ping);

        String wifiName = getInformation.getNewGetInformation(this).getWIFIName();
        if(wifiName.length() > 0){
            if(wifiName.substring(0,1).equals("\"")){
                LogUtil.eE("","进来");
                String wifi = "WiFi："+wifiName.substring(1,wifiName.length()-1);
                textViewName.setText(wifi);
            }else {
                textViewName.setText("WiFi："+wifiName);
            }
        }
        tVsiteareaid.setText(MyApplication.getApp().getSiteAreaid()+"");

        String ipString = getInformation.getNewGetInformation(this).getI_IP();
        mIP = ipString;
        textViewIp.setText("IP地址："+ipString);
        String id = (String)SharedPreferencesUtils.getParam(this,HomeUtil.mUseridDB,"");
        tVid.setText(id);
        mNetwork = getInformation.getNewGetInformation(this).getGateWay();
        textViewMac.setText("MAC："+getInformation.getNewGetInformation(this).getIMAC());
        apMac.setText("apMac:"+getInformation.getNewGetInformation(this).getWiFiMac());
        textViewNetwork.setText("网关："+mNetwork);
        String string  = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mFWQ,"");
        if(!string.equals("")){
            mNetFwq = string.substring(7,string.indexOf(":8"));
            textViewAgentFwq.setText("代理服务器："+mNetFwq);
        }else {
            textViewAgentFwq.setText("代理服务器：没找到");
        }

        mFwq = Url.getUrlNew().getAppIP().substring(7,Url.getUrlNew().getAppIP().indexOf(":8"));
        textViewFWQ.setText("云服务器："+mFwq);

        String fwq = MyApplication.getApp().getFWQString();
        mCurrentFWQ = fwq.substring(7,fwq.indexOf(":8"));
        TViewCurrentFWQ.setText("当前服务器："+mCurrentFWQ);
        internet();
        getPortal();
    }

    /**
     * 状态
     */
    private void internet(){

        HomeUtil.mHUExecutorService.execute(new Runnable() {
            @Override
            public void run() {

                Message msg = new Message();
                Bundle b = new Bundle();// 存放数据
                int ip = StringUtil.getStringUtilNew().getPing(mIP);
                b.putString("type","ip");
                b.putInt("state",ip);
                LogUtil.eE("PING","ip"+ "state     "+ip);
                msg.setData(b);
                mHandler.sendMessage(msg);

                int work = StringUtil.getStringUtilNew().getPing(mNetwork);
                Message msg1 = new Message();
                Bundle b1 = new Bundle();
                b1.putString("type","work");
                b1.putInt("state",work);
                LogUtil.eE("","work"+ "state  "+work);
                msg1.setData(b1);
                mHandler.sendMessage(msg1);

                int netFwq = StringUtil.getStringUtilNew().getPing(mNetFwq);
                Message msg2 = new Message();
                Bundle b2 = new Bundle();
                b2.putString("type","netFwq");
                b2.putInt("state",netFwq);
                LogUtil.eE("","netFwq"+ "state  "+netFwq);
                msg2.setData(b2);
                mHandler.sendMessage(msg2);

                int fwq = StringUtil.getStringUtilNew().getPing(mFwq);
                Message msg3 = new Message();
                Bundle b3 = new Bundle();
                b3.putString("type","fwq");
                b3.putInt("state",fwq);
                LogUtil.eE("","fwq"+ "state  "+fwq);
                msg3.setData(b3);
                mHandler.sendMessage(msg3);

                int niulangGuanWan = StringUtil.getStringUtilNew().getPing(mCurrentFWQ);
                Message msg5 = new Message();
                Bundle b5 = new Bundle();
                b5.putString("type","altair");
                b5.putInt("state",niulangGuanWan);
                LogUtil.eE("","altair"+ "state  "+niulangGuanWan);
                msg5.setData(b5);
                mHandler.sendMessage(msg5);


                int taobao = StringUtil.getStringUtilNew().getPing("www.taobao.com");
                Message msg4 = new Message();
                Bundle b4 = new Bundle();
                b4.putString("type","taobao");
                b4.putInt("state",taobao);
                LogUtil.eE("PING","taobao"+ "state  "+taobao);
                msg4.setData(b4);
                mHandler.sendMessage(msg4);
            }
        });
    }

    /**
     * 去加载portal页面
     */
    private void getPortal(){
        LogUtil.eE("","getPortal()..");
        mWebView = new WebView(this);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://www.szaltair.com/");
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        mWebView.setWebViewClient(new WebViewClient(){
            @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {

                LogUtil.eE("",url+"mJumd"+mJumd);
                try {
                    if(mJumd){
                        if(url.contains("/MobileAltair/")){
                            String string = url.substring(url.indexOf("?")+1,url.length());
                            if(string.contains("ap-mac=")){
                                //String ap_mac = string.substring(string.indexOf("ap-mac=")+7,string.indexOf("&nasip"));
                            }
                            if(string.contains("usermac=") && string.contains("uservlan")){
                                mJumd = false;
                                usermac[0] = string.substring(string.indexOf("usermac=")+8,string.indexOf("&uservlan"));
                                SharedPreferencesUtils.setParam(PingActivity.this, HomeUtil.mFWQMAC, usermac[0]);
                            }

                            if(string.contains("wlanusermac") && string.contains("nasid")){
                                mJumd = false;
                                usermac[0] = string.substring(string.indexOf("wlanusermac=")+12,string.indexOf("&nasid"));
                                SharedPreferencesUtils.setParam(PingActivity.this, HomeUtil.mFWQMAC, usermac[0]);
                            }

                            if(string.contains("nasid")){
                                nasid[0] = string.substring(string.indexOf("nasid")+6,string.length());
                                if(nasid[0].contains("/")){
                                    nasid[0] = nasid[0].replaceAll("/","#");
                                }
                                mTViewNasid.setText("提交(Nasid:"+nasid[0]+")");
                            }
                        }
                        // 是获取的一种样式String Url = "http://172.16.20.203:8080/MobileAltair/jsp/pchome.jsp?userip=172.16.1.12&ac-name=&ssid=altair-SZU&ap-mac=50-DA-00-D1-FD-20&nasip=172.16.1.1&usermac=68-3E-34-63-19-4E&uservlan=2000&userurl=http://baidu.com";
                    }
                }catch (Exception e){
                }
                view.loadUrl(url);
                return true;
            }
        });
    }

    /**
     * 上传 mac  Nasid
     *
     */
    public void pustApMacNasid(String nasid, String apMac){

        mUploadDialog = new UploadDialog(this,"提交中");
        mUploadDialog.show();
        HashMap<String,Object> hashMap = new HashMap<>();
        String token = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mTokenDB, "");
        String id = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mUseridDB, "");
        if(id.equals("")){
            hashMap.put("userid",0);
        }
        if(nasid.equals("")){
            getToast("请稍后，获取中");
            mUploadDialog.dismiss();
            return;
        }
        hashMap.put("userid",id);
        hashMap.put("apMac",apMac);
        hashMap.put("nasid",nasid);
        hashMap.put("apName",getInformation.getNewGetInformation(this).getWIFIName());
        hashMap.put("ip",getInformation.getNewGetInformation(this).getI_IP());
        hashMap.put("mac",getInformation.getNewGetInformation(this).getWiFiMac());
        hashMap.put("siteAreaid",MyApplication.getApp().getSiteAreaid());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(hashMap);
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.getUrlNew().version_testDate,stringJson,token,id,time);
        Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,token,id,Url.getUrlNew().version_testDate,stirngSign,time);
        mLogger.info("pustApMacNasid()--->"+"fwq--"+MyApplication.getApp().getFWQString() + "..stringJson.."+stringJson);
        GreenTreeNetworkUtil.getInstance().doPost(this,MyApplication.getApp().getFWQString(),1,map,new RequestDataCallback() {
            @Override public void onSuccess(String response){
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    mUploadDialog.dismiss();
                    if(jsonObject.getInt("code") == 1){
                        getToast("提交成功");
                        mLogger.info("pustApMacNasid()--->"+"response--"+response);
                    }else {
                        getToast("提交失败");
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    getToast("提交失败");
                }
            }
            @Override
            public void onFailure(Throwable error) {
                mUploadDialog.dismiss();
                StringUtil.getStringUtilNew().getExceptionCode(PingActivity.this,error.toString());
                mLogger.info("pustApMacNasid()--->onFailure()--->失败"+"Throwable--"+error);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWebView.destroy();
        mWebView.removeAllViews();
    }
}
